<?php

/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */
namespace Register\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Register\Form\RegisterForm;
use Zend\View\Model\JsonModel;
use Register\model\Participant;
use Events\model\Register;
use Register\model\ParticipantPhone;
use Register\model\ParticipantEmail;

class IndexController extends AbstractActionController {
	
    protected $form;
	protected $authservice;
	protected $eventTable;
	protected $participantTable;
	protected $registerTable;
	protected $dbConnection;
	protected $participantPhoneTable;
	protected $participantEmailTable;
	
	
	private function processRegistrationData($data) {
	    $data['FK_PARTICIPANT_ID']=$data['ID'];
	    $data['FK_EVENT_ID']=$data['PENDINGEVENT'];
	    return $data;
	}
	
	private function processData($data) {
	    $data['ID']=$this->generateID();
	    return $data;
	}
	
	private function generateID(){
	    $table_key = '1002';
	    $key = $table_key.time();
	    return $key;
	}
	
	public function getDbConnection(){
	    if (! $this->dbConnection) {
	        $this->dbConnection = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter')->getDriver()->getConnection();
	    }
	    return $this->dbConnection;
	}
	
	public function getAuthService() {
	    if (! $this->authservice) {
	        $this->authservice = $this->getServiceLocator ()->get ( 'AuthService' );
	    }
	    return $this->authservice;
	}
	
	public function getUserInfo() {
	    if ($this->getAuthService ()->getIdentity ()) {
	        $this->userinfo = $this->getAuthService ()->getStorage ()->read ();
	    }
	    return $this->userinfo;
	}
	
	public function getEventTable() {
		if (! $this->eventTable) {
			$this->eventTable = $this->getServiceLocator ()->get ( 'Event\Model\EventTable' );
		}
		return $this->eventTable;
	}
	
	public function getParticipantTable() {
	    
	    if (! $this->participantTable) {
	        $this->participantTable = $this->getServiceLocator ()->get ( 'Register\Model\ParticipantTable' );
	    }
	    return $this->participantTable;
	}
	
	public function getParticipantPhoneTable()
	{
	    if(! $this->participantPhoneTable) {
	        $this->participantPhoneTable = $this->getServiceLocator()->get('Register\Model\ParticipantPhoneTable');
	    }
	    return $this->participantPhoneTable;
	}
	
	public function getParticipantEmailTable()
	{
	    if(! $this->participantEmailTable) {
	        $this->participantEmailTable = $this->getServiceLocator()->get('Register\Model\ParticipantEmailTable');
	    }
	    return $this->participantEmailTable;
	}
	
	public function getRegisterTable()
	{
	    if(! $this->registerTable) {
	        $this->registerTable = $this->getServiceLocator()->get('Event\Model\RegisterTable');
	    }
	    return $this->registerTable;
	}
	
	protected function createParticipant(array $data,$type)
	{
	    $participant=new Participant();
	    $participant->exchangeArray($data);
	    $participant_phone=new ParticipantPhone();
	    $participant_phone->exchangeArray($data);
	    $participant_email=new ParticipantEmail();
	    $participant_email->exchangeArray($data);
	    
	    $this->getParticipantTable()->saveParticipant($participant,$type);
	    $this->getParticipantPhoneTable()->saveParticipantPhone($participant_phone, $type);
	    $this->getParticipantEmailTable()->saveParticipantEmail($participant_email, $type);
	    return true;
	}
	protected function createRegister(array $data)
	{
	    $register=new Register();
	    $register->exchangeArray($data);
	    $this->getRegisterTable()->saveRegister($register);
	    return true;
	}
	/* Actions */

	public function rolecomboAction() {
	    
	   if ($this->getAuthService ()->getIdentity ()) {
	    if(isset($_POST['textData']) && !($_POST['textData']==0))
	        {   
        		$id = $_POST['textData'];
        		$result=$this->getEventTable()->getEvent($id);
        		 
        		return new JsonModel([
        				'title'=>$result->SUBJECT,
        				'place'=>$result->PLACE,
        				'date'=>$result->DATE
        		]);
	        }
	   }
	   return $this->redirect ()->toRoute ( 'Login' );
	}
	
	public function getParticipantDataAction() {
	     
	    if ($this->getAuthService ()->getIdentity ()) {
	        if(isset($_POST['textData']) && !($_POST['textData']==0))
	        {
	            $phone = $_POST['textData'];
	            $result=$this->getParticipantPhoneTable()->getParticipant($phone);
	            $participant_Email=$this->getParticipantEmailTable()->getParticipantEmail($result->ID);
	            $participant=$this->getParticipantTable()->getParticipant($result->ID);
	            
	            $participated_events=$this->getRegisterTable()->getParticipatedEvents($result->ID);
	            foreach ($participated_events as $event){
	                $events []=$event;
	            }
	            
	            return new JsonModel([
        	           'ID' => $participant->ID,
	                   'EMAIL' => $participant_Email->EMAIL,
                       'TITLE' => $participant->TITLE,
                       'GENDER'  => $participant->GENDER,
                       'FIRST_NAME' => $participant->FIRST_NAME,
                       'MIDDLE_NAME' => $participant->MIDDLE_NAME,
                       'LAST_NAME' => $participant->LAST_NAME,
                       'ADDRESS' =>$participant->ADDRESS,
                       'NEAREST_CITY'=>$participant->NEAREST_CITY,
                       'FUNDING' =>$participant->FUNDING,
                       'ORGANIZATION' =>$participant->ORGANIZATION,
	                   'EVENTS'=> json_encode($events),
	            ]);
	        }
	    }
	    return $this->redirect ()->toRoute ( 'Login' );
	}
	
	public function indexAction() {
		if ($this->getAuthService ()->getIdentity ()) {
		    
		    $userinfo = $this->getUserInfo ();
		    $this->layout ()->role = $userinfo->ROLE;
		    $this->layout ()->user = $userinfo->USERNAME;
			
			if (! $userinfo->ROLE == 'admin') {
				return $this->redirect ()->toRoute ( 'Login' );
			}
			
			$form = new RegisterForm();
			$pendingEvent = $this->getEventTable ()->fetchPendingEvents ();
			
			$viewmodel = new ViewModel ( array (
					'form' => $form,
					'eventList' => $pendingEvent,
			        'flashMessages' => $this->flashMessenger()->getMessages()
			) );
			
			return $viewmodel;
		}
		
		return $this->redirect ()->toRoute ( 'Login' );
	}
	
	public function processAction() {
	    
		if ($this->getAuthService ()->getIdentity ()) {
			
			$userinfo = $this->getUserInfo ();
			$this->layout ()->role = $userinfo->ROLE;
			$this->layout ()->user = $userinfo->USERNAME;
			
			if (! $this->request->isPost ()) {
				return $this->redirect ()->toRoute ( NULL, array (
						'controller' => 'index',
						'action' => 'index' 
				) );
			}			
			
			$form = new RegisterForm ();
			$pendingEvent = $this->getEventTable ()->fetchPendingEvents ();
			
			$post = $this->request->getPost ();
			$form->setData ( $post );
		  

			if (! $form->isValid ()) {
				$model = new ViewModel ( array (
						'form' => $form,				        
						'eventList' => $pendingEvent 
				) );
				$model->setTemplate ( 'register/index/index' );
				return $model;
			}
			
			$data=$form->getData();
			$this->getDbConnection()->beginTransaction();
			try{ 
        			if(!isset($data['ID'])||$data['ID']==0){
        			    $data = $this->processData($data);
        			    $this->createParticipant($data,0);
        			}
        			else{
        			    $this->createParticipant($data,1);
        			}        			
        			
        			$data=$this->processRegistrationData($data);
        		    $this->createRegister($data);			
        			
        			$this->flashMessenger()->addMessage('Participant '.$data['FIRST_NAME']." ".$data['LAST_NAME'].' is sucessfully added!');
        			$this->getDbConnection()->commit();
		    }
			catch (\Exception $ex){
			    $this->getDbConnection()->rollback();
			    $this->flashMessenger()->addMessage('Participant registration is failed!');
			} 			
			return $this->redirect()->toRoute('register',array( 'controller'=> 'index','action' => 'index'));
			
		} else {
			return $this->redirect ()->toRoute ( 'Login' );
		}
	}
	
/* 	public function checkEventStatusAction() {
	    
	   if ($this->getAuthService ()->getIdentity ()) {
	    if(isset($_POST['textData']) && !($_POST['textData']==0))
	        {   
        		$id = $_POST['textData'];
        		$result=$this->getEventTable()->getEvent($id);
        		 
        		return new JsonModel([
        				'title'=>$result->,
        		]);
	        }
	   }
	   return $this->redirect ()->toRoute ( 'Login' );
	} */
}

